package cn.git.shiro.util;

import cn.hutool.core.util.StrUtil;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 日志通用方法
 *
 * @program: bank-credit-sy
 * @author: liudong
 * @create: 2022-06-15
 */
public class LogUtil {

    /**
     * 日志长度
     */
    public static final Integer LENGTH_INT_0 = 0;
    public static final Integer LENGTH_INT_1000 = 1000;
    public static final Integer LENGTH_INT_2000 = 2000;
    public static final Integer LENGTH_INT_3500 = 3500;

    /**
     * 打印异常信息转字符串
     *
     * @param exception 异常
     * @return 异常信息
     */
    public static String getStackTraceInfo(Exception exception) {
        return getStackTraceInfo(exception, LENGTH_INT_1000);
    }

    /**
     * 打印异常信息转字符串
     *
     * @param exception          异常
     * @param errorMessageLength 打印异常信息长度
     * @return 异常信息
     */
    public static String getStackTraceInfo(Exception exception, Integer errorMessageLength) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        try {
            exception.printStackTrace(printWriter);
            printWriter.flush();
            stringWriter.flush();
            String errorMessage = stringWriter.toString();
            if (StrUtil.isNotBlank(errorMessage) && errorMessage.length() > LENGTH_INT_3500) {
                errorMessage =
                        errorMessage.substring(LENGTH_INT_0, errorMessageLength);
            }
            return errorMessage;
        } finally {
            try {
                printWriter.close();
                stringWriter.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

}
